<script lang="ts" setup>
import { defineEmits, ref } from 'vue'

const emit = defineEmits()
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const fileList = ref([] as any[])

const coverImage = ref('') // Base64 图片

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}

const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

const handleUploadChange = async ({ file }: any) => {
  if (file.status === 'done' || file.originFileObj) {
    coverImage.value = (await getBase64(file.originFileObj)) as string
    // 向父组件传递封面图片
    emit('update:coverImage', coverImage.value) // 通过事件传递图片
  }
}
</script>

<template>
  <div class="clearfix">
    <a-form-item label="文章封面">
      <a-upload
        v-model:file-list="fileList"
        list-type="picture-card"
        @preview="handlePreview"
        @change="handleUploadChange"
      >
        <div v-if="fileList!.length < 1">
          <plus-outlined />
          <div style="margin-top: .5rem">上传封面</div>
        </div>
      </a-upload>
    </a-form-item>

    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style=" width: 15.625rem;height: 15.625rem" :src="previewImage" />
    </a-modal>
  </div>
</template>
